package com.heatup.apt.api.controller;

import com.alibaba.druid.util.StringUtils;
import com.heatup.apt.api.service.OrderService;
import com.heatup.apt.api.service.ProductServiceInterface;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.util.*;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.user.UserInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 产品
 *
 * @author Jindaodaxia
 */
@Controller
@RequestMapping("/product")
public class ProductController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(ProductController.class);

    @InitBinder
    public void initBinder(WebDataBinder dataBinder, Locale locale, HttpServletRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,true));
    }

    @Autowired
    private ProductServiceInterface productService;
    
    @Autowired
    private OrderService orderService;
    

    /**
     * 会员价格表
     */
    @ResponseBody
    @RequestMapping(value = "/viplist", method = {RequestMethod.POST, RequestMethod.GET})
    private String getVipProductList(HttpServletRequest request) {

        String callback = RequestTools.RequestString(request, "callback", "");
        Integer productId = RequestTools.RequestInt(request, "productId", 1);// add jxy 

        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<Map<String, Object>>();
        apiResultModel.setLogined(this.isLogined());

        //未登陆
        if (!isLogined()) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }

        try {
            Map<String, Object> map = productService.getViplist(this.getUserId(),productId);
            map.put("userAccount", this.getUserInfo().getAccountAmt());
            apiResultModel.setData(map);
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            apiResultModel.setMsg("");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage()+ e.toString() + e.getCause());
        }
        apiResultModel.setLogined(this.isLogined());
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 获取产品信息 用于订单页面
     */
    @ResponseBody
    @RequestMapping(value = "/productlist", method = {RequestMethod.POST, RequestMethod.GET})
    private String getProductList(HttpServletRequest request) {

        String callback = RequestTools.RequestString(request, "callback", "");
        int serviceType = RequestTools.RequestInt(request, "type", 0);
        int storeId = RequestTools.RequestInt(request, "storeId", 0);
        int courseId = RequestTools.RequestInt(request, "courseId", 0);
        String longitudeLatitude = RequestTools.RequestString(request, "longitudeLatitude", "");

        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<Map<String, Object>>();


        //未登陆
        if (!isLogined()) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }

        try {
            int userLevel = this.getUserInfo().getLevel();
//            apiResultModel.setData(productService.getProductList(userLevel, serviceType, storeId, courseId,getUserInfo().getAccountAmt()));
            apiResultModel.setData(productService.getProductList(userLevel, serviceType, storeId, courseId, getUserInfo(), longitudeLatitude));
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            apiResultModel.setMsg("");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString()+ e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause());
        }
        apiResultModel.setLogined(this.isLogined());
        return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStrWithDateFormat(apiResultModel), callback);
    }

    /**
     * 校验支付类型
     *
     * @param request 请求
     * @param courseId 课程 ID
     * @param selfTime 自助健身时间
     * @return 返回可用的支付类型
     */
    @ResponseBody
    @RequestMapping(value = "/checkPayTypeAndPriceAndPersonCount", method = {RequestMethod.POST, RequestMethod.GET})
    public String checkPayTypeAndPriceAndPersonCount(HttpServletRequest request,String courseId, Date selfTime, String callback){
		int courseIdT = 0;
		if (StringUtils.isEmpty(courseId) || courseId.equals("undefined")) {
			courseId = null;
		} else {
			courseIdT = Integer.parseInt(courseId);
		}

		int serviceType = RequestTools.RequestInt(request, "serviceType", 0);
		int storeId = RequestTools.RequestInt(request, "storeId", 0);
		Integer serviceId = RequestTools.RequestInt(request, "serviceId", 0);
		Integer productId = RequestTools.RequestInt(request, "productId", 0);
        Integer orderId = RequestTools.RequestInt(request, "orderId", 0);
		ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<Map<String, Object>>();
		apiResultModel.setLogined(this.isLogined());
		UserInfo userInfo = this.getUserInfo();
		Map<String,Object> paramsMap = new HashMap<>();
		
		// 未登陆
		if (!isLogined()) {
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
			apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
			return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
		}
		try {
			if(serviceType < 5 || serviceType == 9 || serviceType == 10){
				paramsMap = orderService.checkPayOrderType(userInfo, courseIdT, serviceType, storeId, selfTime,orderId);
			}else if(serviceType == 5 || serviceType == 7){
				paramsMap = orderService.checkPayCarMonthOrderType(userInfo, serviceId, productId);
			}
			if(paramsMap == null){
				apiResultModel.setRet(ApiResultModel.RET_ERROR);
				apiResultModel.setMsg("商品不存在");
				return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStrWithDateFormat(apiResultModel), callback);
			}
			apiResultModel.setData(paramsMap);
			apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
			apiResultModel.setMsg("");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause(), e);
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
			apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
			apiResultModel
					.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause());
		}
		return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStrWithDateFormat(apiResultModel), callback);
    }

    /**
     * 检验自助健身订单数量
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkStoreSelfOrderCount")
    public String checkStoreSelfOrderCount(HttpServletRequest request){
            Integer storeId = RequestTools.RequestInt(request,"storeId",1);
            String  selfTime = RequestTools.RequestString(request,"selfTime",null);
            String  callback = RequestTools.RequestString(request,"callback","");
            if(selfTime ==null){
                selfTime = DateUtils.format(new Date(),DateUtils.datePatternAllHH);
            }
             ApiResultModel apiResultModel = new ApiResultModel();
        // 未登陆
        if (!isLogined()) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }
        try{
            Map<String,Object> respMap = orderService.checkStoreSelfOrderCount(storeId,selfTime);
            apiResultModel.setData(respMap);
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
        }catch (Exception e){
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("判断门店当前预订时间订单数量异常");
            e.printStackTrace();
            logger.error("判断门店当前预订时间订单数量异常：" ,e);
        }
        apiResultModel.setLogined(isLogined());

         return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStrWithDateFormat(apiResultModel), callback);
    }
}
